package com.my.lucky.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.my.lucky.util.WenTest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class IwencaiService {

    private final String IWENCAI_URL = "https://www.iwencai.com/customized/chart/get-robot-data";

    public JSONObject searchStocksD(String keyword) {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        // 设置必要的请求头
        headers.set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36 Edg/134.0.0.0");
        headers.set("Accept", "application/json, text/plain, */*");
        WenTest wenTest = new WenTest();
        long serverTime = System.currentTimeMillis() / 1000;
        String token = wenTest.getToken(serverTime);
        headers.set("hexin-v", token); // 使用动态生成的 hexin-v 值
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("source", "Ths_iwencai_Xuangu");
        requestBody.put("version", "2.0");
        requestBody.put("query_area", "");
        requestBody.put("block_list", "");
        requestBody.put("add_info", "{\"urp\":{\"scene\":1,\"company\":1,\"business\":1},\"contentType\":\"json\",\"searchInfo\":true}");
        requestBody.put("secondary_intent", "stock");
        requestBody.put("log_info", "{\"input_type\":\"click\"}");
        requestBody.put("rsh", "Ths_iwencai_Xuangu_eltocjq2aj9ertsvh3kz3ubqd3zlkvaa");
        requestBody.put("question", keyword);
        requestBody.put("perpage", 50);
        requestBody.put("page", 1);
        HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, headers);

        try {
            ResponseEntity<String> response = restTemplate.exchange(
                    IWENCAI_URL,
                    HttpMethod.POST,
                    entity,
                    String.class
            );

            if (response.getStatusCode() == HttpStatus.OK) {
                JSONObject jsonResponse = JSON.parseObject(response.getBody());
                return jsonResponse.getJSONObject("data").getJSONArray("answer")
                        .getJSONObject(0).getJSONArray("txt")
                        .getJSONObject(0).getJSONObject("content")
                        .getJSONArray("components").getJSONObject(0)
                        .getJSONObject("data");
            }
        } catch (Exception e) {
            log.error("weincai error", e);
        }
        return null;
    }

    public List<Map<String, Object>> searchStocks(String keyword) {
        log.info("开始处理问句查询");
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        // 设置必要的请求头
        headers.set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36 Edg/134.0.0.0");
        headers.set("Accept", "application/json, text/plain, */*");

        WenTest wenTest = new WenTest();
        long serverTime = System.currentTimeMillis() / 1000;
        String token = wenTest.getToken(serverTime);
        //    System.out.println(token);
        headers.set("hexin-v", token); // 使用动态生成的 hexin-v 值
        //  headers.set("referer", "https://www.iwencai.com/unifiedwap/result?w=%E8%B6%8B%E5%8A%BF&querytype=stock");
        // headers.set("cookie", "other_uid=Ths_iwencai_Xuangu_eltocjq2aj9ertsvh3kz3ubqd3zlkvaa; ta_random_userid=9unaj7b8k5; cid=cf47e1317f057548b98926989a8e94b51747824747; v=A_7Us39DGpmiI0698oXoK4vjTx9FP8K5VAN2nagHasE8S5CBEM8SySSTxqp7");

        Map<String, Object> requestBody = new HashMap<>();
        /**
         * {"source":"Ths_iwencai_Xuangu","version":"2.0","query_area":"","block_list":"",
         * "add_info":"{\"urp\":{\"scene\":1,\"company\":1,\"business\":1},\"contentType\":\"json\",\"searchInfo\":true}",
         * "question":"趋势",
         * "perpage":50,"page":1,
         * "secondary_intent":"stock",
         * "log_info":"{\"input_type\":\"click\"}",
         * "rsh":"Ths_iwencai_Xuangu_eltocjq2aj9ertsvh3kz3ubqd3zlkvaa"}
         */
        requestBody.put("source", "Ths_iwencai_Xuangu");
        requestBody.put("version", "2.0");
        requestBody.put("query_area", "");
        requestBody.put("block_list", "");
        requestBody.put("add_info", "{\"urp\":{\"scene\":1,\"company\":1,\"business\":1},\"contentType\":\"json\",\"searchInfo\":true}");
        requestBody.put("secondary_intent", "stock");
        requestBody.put("log_info", "{\"input_type\":\"click\"}");
        requestBody.put("rsh", "Ths_iwencai_Xuangu_eltocjq2aj9ertsvh3kz3ubqd3zlkvaa");
        requestBody.put("question", keyword);
        requestBody.put("perpage", 50);
        requestBody.put("page", 1);
        HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, headers);

        try {
            ResponseEntity<String> response = restTemplate.exchange(
                    IWENCAI_URL,
                    HttpMethod.POST,
                    entity,
                    String.class
            );
            //   System.out.println(JSONUtil.toJsonStr(response));
            if (response.getStatusCode() == HttpStatus.OK) {
                JSONObject jsonResponse = JSON.parseObject(response.getBody());
                JSONArray data = jsonResponse.getJSONObject("data").getJSONArray("answer")
                        .getJSONObject(0).getJSONArray("txt")
                        .getJSONObject(0).getJSONObject("content")
                        .getJSONArray("components").getJSONObject(0)
                        .getJSONObject("data").getJSONArray("datas");


                List<Map<String, Object>> stocks = new ArrayList<>();
                for (int i = 0; i < data.size(); i++) {
                    JSONObject stock = data.getJSONObject(i);
                    //    System.out.println(stock.toJSONString());
                    Map<String, Object> stockMap = new HashMap<>();
                    stockMap.put("code", stock.getString("股票代码"));
                    stockMap.put("name", stock.getString("股票简称"));
                    stockMap.put("price", stock.getDouble("最新价"));
                    stockMap.put("changePercent", stock.getDouble("涨跌幅"));
                    stockMap.put("open", stock.getDouble("开盘价"));
                    stockMap.put("high", stock.getDouble("最高价"));
                    stockMap.put("low", stock.getDouble("最低价"));
                    stocks.add(stockMap);
                }
                return stocks;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ArrayList<>();
    }
} 